<template>
  <div class="user-center-container">
    <div class="user-info-box">
      <van-image
        class="user-info-avatar"
        round
        :src="user.avatar"
      />
      <div class="user-info-name">
        {{ user.username || user.nickname }}
      </div>
    </div>
    <div class="user-info-group">
      <van-cell title="我的订单" icon="orders-o" is-link @click="toUrl('/order')"/>
    </div>
    <div class="user-actions">
      <van-button plain type="info" block @click="onLogout" :loading="submitting" loading-text="登出中...">登出</van-button>
    </div>
  </div>
</template>

<script>
export default {
  data: function () {
    return {
      submitting: false
    }
  },
  created () {
    this.fetchUser()
  },
  computed: {
    user () {
      return this.$store.state.user.user
    }
  },
  methods: {
    fetchUser () {
      if (!this.user) {
        this.$store.dispatch('fetchUser')
          .catch((err) => this.$toast(err.message))
      }
    },
    toUrl (path) {
      this.$router.push({
        path: path
      })
    },
    onLogout () {
      this.submitting = true
      this.$store.dispatch('logout').then(() => {
        this.submitting = false
        this.$router.replace({ path: 'home' })
      }).catch(() => {
        this.submitting = false
      })
    }
  }
}
</script>

<style lang="less">
  .user-center-container {
    .user-info-box {
      text-align: center;
      padding: 20px 0;
    }

    .user-info-avatar {
      width: 100px;
      height: 100px;
    }

    .user-info-name {
      margin-top: 10px;
    }

    .user-actions {
      margin-top: 20px;
      padding: 20px;
    }
  }
</style>
